package com.geekgo.lucenepp.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.geekgo.lucenepp.core.config.doc.Documents;
import com.geekgo.lucenepp.model.Field;
import org.apache.lucene.document.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * document工具
 *
 * @author HeHaoyang
 * @create 2017-06-14 10:55
 **/
public final class DocumentUtil {

    private static final Logger logger = LoggerFactory.getLogger(DocumentUtil.class);


    public static List<Document> objtodoc(List<Object> objectList, List<Field> fieldList){
        List<Document> documents = new ArrayList<>();
        objectList.forEach(o -> documents.add(objtodoc(o,fieldList)));
        return documents;
    }

    public static Document objtodoc(Object object,List<Field> fieldList){
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(object));
        Documents doc = new Documents();
        fieldList.forEach(field -> {
            String name = field.getName();
            Object boostObj = jsonObject.get("boost");
            if(null != boostObj){
                doc.put(name,jsonObject.get(name),field.getType(),Float.valueOf(boostObj.toString()));
            }else{
                doc.put(name,jsonObject.get(name),field.getType(),field.getBoost());
            }
        });
        return doc.getDocument();
    }

    public static List<Document> maptodoc( List<HashMap> list, List<Field> fieldList){
        List<Document> documents = new ArrayList<>();
        int size = list.size();
        for (int i = 0; i < size; i++) {
            HashMap<?, ?> hashMap = list.get(i);
            Documents doc = new Documents();
            int size_ = fieldList.size();
            for (int j = 0; j < size_; j++) {
                Field field = fieldList.get(j);
                String name = field.getName();
                doc.put(name, hashMap.get(name),field.getType(),field.getBoost());

            }
            documents.add(doc.getDocument());
        }
        return documents;
    }

}
